package com.leyou.auth.config;

import com.leyou.auth.utils.RsaUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@Data
@ConfigurationProperties("ly.jwt")
public class JwtProperties {

    private String secret;
    private String pubKeyPath;
    private String priKeyPath;
    private int expire;

    private String cookieName;


    private PublicKey publicKey;  //公钥
    private PrivateKey privateKey;//私钥

    //类对象实例化后，就应该读取公钥和私钥

    @PostConstruct   // 等效为 bean标签中的init-method属性
    public void init() throws Exception {
            //公钥和私钥如果不存在，先生成
        File pubPath = new File(pubKeyPath);
        File priPath = new File(priKeyPath);
        if(!pubPath.exists() || !priPath.exists()){ //如果任意一个不存在，则生成
            RsaUtils.generateKey(pubKeyPath,priKeyPath,secret);
        }

            //如果公钥私钥不存在抛出异常
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
    }
}
